# pythonchallenge.com scripts
# challenge #7
# url: http://www.pythonchallenge.com/pc/def/oxygen.html
# -> http://www.pythonchallenge.com/pc/def/pants.html : amazing. zoom in
# ref: http://www.pythonware.com/products/pil/index.htm

# load modules
import cfg, sys


# ----------------------------------------------------------------------------
# Conjecture 1: we do something with the image file

# our png file
pc_png = cfg.challenge_dir + '\\oxygen.png'
imgz_path = cfg.challenge_dir + '\\oxygen.zoom.png'

# modules
import Image

# test PIL
Img = Image.open(pc_png)
print Img.format, Img.size, Img.mode

# info
for k,v in Img.info.iteritems(): print k,v

# histogram
if False:
  for i, x in enumerate(Img.histogram()):
    print i, x,
  
# get bands
for b in Img.getbands(): print b

# let's split
ext = '.png'
fns = ['r', 'g', 'b', 'a']
for fn, imgb in zip(fns,Img.split()):
  imgb.save(cfg.challenge_dir + '//oxygen_' + fn + ext)
  
# get data
for i, px in enumerate(Img.getdata()):
  continue
  if ( px[0] == px[1] == px[2] ):
    print "gray: " + str(i), str(px)
  elif ( px[3] != 255 ):
    print "a<>255: " + str(i), str(px[3])
    

    
# cycle through image
num_px = Img.size[0] * Img.size[1]
print "num of px: " + str(Img.size[0]) + " x " + str(Img.size[1]) + " = " + str(num_px)

# collect anomalies
ACHNL = []
for h in range(Img.size[1]):
  for w in range(Img.size[0]):
    px = Img.getpixel((w,h))
    if ( px[3] != 255 ) :
      ACHNL.append((w,h))
print ACHNL       

      

GRAY = ALPHA = []
for h in range(Img.size[1]):
  #if h > 200: cfg.breakpoint()
  for w in range(Img.size[0]):
    px = Img.getpixel((w,h))
    if ( px[0] == px[1] == px[2] ):
      GRAY.append((w,h))
    elif ( px[3] != 255 ):
      ALPHA.append((w,h))
      
print "len(GRAY) " + str(len(GRAY))
print "len(ALPHA) " + str(len(ALPHA))

# remove alpha channel
ipath = cfg.challenge_dir + '//oxygen.rgb' + ext
ImgRgb = Img.convert("RGB")
ImgRgb.save(ipath)
print ImgRgb.format, ImgRgb.size, ImgRgb.mode

# recolor the alpha anomalies
ipath = cfg.challenge_dir + '//oxygen.gray' + ext
Pxl = ImgRgb.load()
for xy in GRAY: 
  x = xy[0]
  y = xy[1]
  RGB = Pxl[xy]
  Pxl[(x,y)] = (10, 10, 200, 0)
ImgRgb.save(ipath)

# list pixel results
for i in range(500):
  gval = ACHNL[i] 
  gpix = Pxl[gval]
  print i, gval, gpix
        
      
#cfg.breakpoint()
  


# scale
zoomx = 10
neww = Img.size[0] * zoomx
newh = Img.size[1] * zoomx
fltr = Image.NEAREST   # NEAREST, BILINEAR, BICUBIC, ANTIALIAS 
NewImg = Img.resize((neww,newh), fltr)
NewImg.save(imgz_path)


# ----------------------------------------------------------------------------
# zoom fx

def zoom_img(img_path, zoom_factor=1.5):
  Img = Image.open(img_path)
  w = Img.size(0) * zoom_factor
  h = Img.size(1) * zoom_factor
  NewImg = Img.resize((w,h))
  return NewImg


print "end ch7"
